export default {
  name: 'cityDialog',
  props: {
    isVisible: Boolean,
    isTip: Boolean,
    isCheckbox: Boolean,
    cityData: Array
  },
  data() {
    return {
      showClose: false,
      city: [],
      hotCitys: [],
      allProvinces: [], // 所有省份
      oneCity: [], // 直辖市
      currentProvince: '',
      isShow: true
    }
  },
  created() {
    this.city = this.cityData;
    this.getCity();
    this.getHotCity();
  },
  watch: {
    cityData: function (newVal) {
      this.city = newVal
    }
  },
  methods: {
    // 获取所有城市
    getCity() {
      this.$http.get('./assets/citys.json').then(res => {
        let obj = res.body.city;
        for (let i = 0; i < obj.length; i++) {
          if (obj[i].subLevelModelList.length === 1) {
            this.oneCity.push(obj[i]);
          } else {
            this.allProvinces.push(obj[i]);
          }
        }
      })
    },
    // 获取热门城市
    getHotCity() {
      this.$axios.post('/system/v1/common/dict', {
        groupid: 'hotcity'
      }).then(res => {
        this.hotCitys = res.data.data;
      })
    },
    // 去重已选城市
    delRepeat(name, code) {
      let item = {};
      item.name = name;
      item.code = code;
      if (!this.city.length) {
        this.city.push(item);
      } else if (this.city.length === 1 && this.city[0].name === '全国') {
        this.city.splice(0, this.city.length, item);
      } else {
        if (!this.isCheckbox || name === '全国') {
          this.city.splice(0, this.city.length, item);
        } else {
          let flag = true;
          this.city.forEach(el => {
            if (el.name === name) {
              flag = false;
            }
          });
          if (flag) {
            this.city.push(item);
          }
        }
      }
    },
    // 选择热门城市
    selectedHotCity(name, code) {
      this.delRepeat(name, code)
    },
    // 选择省份下属城市
    handleCommand(command) {
      this.delRepeat(command.name, command.code)
    },
    // 选择直辖市或特别行政区
    specialHandle(name, code) {
      this.delRepeat(name, code);
    },
    // 选择全国
    selectedNationwide() {
      let name = '全国';
      let code = '999';
      this.delRepeat(name, code);
    },
    // 删除当前项城市
    closeCity(index) {
      this.city.splice(index, 1);
    },
    // 确认当前选择城市
    confirm() {
      if (this.city) {
        this.$emit('getSelectCity', this.city);
        this.$emit('closeDialog', false);
      } else {
        this.$message('您还未选择城市, 请选择城市');
      }
    },
    // 点击取消按钮，关闭城市选择对话框
    cancel() {
      this.$emit('closeDialog', false);
    }
  }
}